
/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2023原作者。
 *
 *根据Apache许可证2.0版（“许可证”）获得许可；
 *除非符合许可证，否则不得使用此文件。
 *您可以在以下地址获取许可证副本：
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，软件
 *根据许可证分发的内容是按“原样”分发的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限和
 *许可证下的限制。
 */

package org.springframework.beans.factory.config;

import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.lang.Nullable;
import org.springframework.util.StringValueResolver;

/**
 * Abstract base class for property resource configurers that resolve placeholders
 * in bean definition property values. Implementations <em>pull</em> values from a
 * properties file or other {@linkplain org.springframework.core.env.PropertySource
 * property source} into bean definitions.
 *
 * <p>The default placeholder syntax follows the Ant / Log4J / JSP EL style:
 *
 * <pre class="code">${...}</pre>
 *
 * Example XML bean definition:
 *
 * <pre class="code">
 * &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
 *   &lt;property name="driverClassName" value="${driver}" /&gt;
 *   &lt;property name="url" value="jdbc:${dbname}" /&gt;
 * &lt;/bean&gt;
 * </pre>
 *
 * Example properties file:
 *
 * <pre class="code">
 * driver=com.mysql.jdbc.Driver
 * dbname=mysql:mydb</pre>
 *
 * Annotated bean definitions may take advantage of property replacement using
 * the {@link org.springframework.beans.factory.annotation.Value @Value} annotation:
 *
 * <pre class="code">@Value("${person.age}")</pre>
 *
 * Implementations check simple property values, lists, maps, props, and bean names
 * in bean references. Furthermore, placeholder values can also cross-reference
 * other placeholders, like:
 *
 * <pre class="code">
 * rootPath=myrootdir
 * subPath=${rootPath}/subdir</pre>
 *
 * In contrast to {@link PropertyOverrideConfigurer}, subclasses of this type allow
 * filling in of explicit placeholders in bean definitions.
 *
 * <p>If a configurer cannot resolve a placeholder, a {@link BeanDefinitionStoreException}
 * will be thrown. If you want to check against multiple properties files, specify multiple
 * resources via the {@link #setLocations locations} property. You can also define multiple
 * configurers, each with its <em>own</em> placeholder syntax. Use {@link
 * #ignoreUnresolvablePlaceholders} to intentionally suppress throwing an exception if a
 * placeholder cannot be resolved.
 *
 * <p>Default property values can be defined globally for each configurer instance
 * via the {@link #setProperties properties} property, or on a property-by-property basis
 * using the value separator which is {@code ":"} by default and customizable via
 * {@link #setValueSeparator(String)}.
 *
 * <p>Example XML property with default value:
 *
 * <pre class="code">
 *   &lt;property name="url" value="jdbc:${dbname:defaultdb}" /&gt;
 * </pre>
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @since 3.1
 * @see PropertyPlaceholderConfigurer
 * @see org.springframework.context.support.PropertySourcesPlaceholderConfigurer
 */
/**
 *解析占位符的属性资源配置器的抽象基类
 *在bean定义属性值中。实现<em>从
 *财产文件或其他{@linkplain org.springframework.core.env.PropertySource
 *属性源}转换为bean定义。
 *
 *＜p＞默认占位符语法遵循Ant/Log4J/JSP EL样式：
 *
 *<pre-class=“code”>$｛…｝</pre>
 *
 *XML bean定义示例：
 *
 *<pre-class=“code”>
 *&lt；bean id=“dataSource”class=“org.springframework.jdb.dataSource.DriverManagerDataSource”&gt；
 *&lt；property name=“driverClassName”value=“${driver}”/&gt；
 *&lt；property name=“url”value=“jdbc:$｛dbname｝”/&gt；
 *&lt/豆&gt；
 *</pre>
 *
 *财产文件示例：
 *
 *<pre-class=“code”>
 *driver=com.mysql.jdbc.driver
 *dbname=mysql:mydb</pre>
 *
 *带注释的bean定义可以使用
 *｛@link org.springframework.beans.factory.annotation.Value@Value｝注释：
 *
 *<pre-class=“code”>@Value（“${person.age}”）</pre>
 *
 *实现检查简单属性值、列表、映射、props和bean名称
 *在bean引用中。此外，占位符值也可以交叉引用
 *其他占位符，如：
 *
 *<pre-class=“code”>
 *rootPath=myrootdir
 *subPath=$｛rootPath｝/subdir</pre>
 *
 *与｛@link PropertyOverrideConfigurer｝相反，此类型的子类允许
 *在bean定义中填充显式占位符。
 *
 *＜p＞如果配置者无法解析占位符，则会出现｛@link BeanDefinitionStoreException｝
 *将被抛出。如果要检查多个财产文件，请指定多个
 *资源。您还可以定义多个
 *配置器，每个都有自己的</em>占位符语法。使用｛@link
 *#ignoreUnsolvablePlaceholders｝在
 *无法解析占位符。
 *
 *＜p＞可以为每个配置器实例全局定义默认属性值
 *通过{@link#setProperties财产属性，或基于property-by-property
 *使用值分隔符，默认情况下为｛@code“：”｝，可通过
 *｛@link#setValueSeparator（字符串）｝。
 *
 *＜p＞具有默认值的示例XML属性：
 *
 *<pre-class=“code”>
 *&lt；property name=“url”value=“jdbc:$｛dbname:defaultdb｝”/&gt；
 *</pre>
 *
 *@作者Chris Beams
 *@作者Juergen Hoeller
 *@自3.1
 *@参见PropertyPlaceholderConfigurator
 *@请参见org.springframework.context.support.PropertySourcesPlaceholderConfigurator
 */
public abstract class PlaceholderConfigurerSupport extends PropertyResourceConfigurer
		implements BeanNameAware, BeanFactoryAware {

	/** Default placeholder prefix: {@value}. */
	public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

	/** Default placeholder suffix: {@value}. */
	public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

	/** Default value separator: {@value}. */
	public static final String DEFAULT_VALUE_SEPARATOR = ":";


	/** Defaults to {@value #DEFAULT_PLACEHOLDER_PREFIX}. */
	protected String placeholderPrefix = DEFAULT_PLACEHOLDER_PREFIX;

	/** Defaults to {@value #DEFAULT_PLACEHOLDER_SUFFIX}. */
	protected String placeholderSuffix = DEFAULT_PLACEHOLDER_SUFFIX;

	/** Defaults to {@value #DEFAULT_VALUE_SEPARATOR}. */
	@Nullable
	protected String valueSeparator = DEFAULT_VALUE_SEPARATOR;

	protected boolean trimValues = false;

	@Nullable
	protected String nullValue;

	protected boolean ignoreUnresolvablePlaceholders = false;

	@Nullable
	private String beanName;

	@Nullable
	private BeanFactory beanFactory;


	/**
	 * Set the prefix that a placeholder string starts with.
	 * The default is {@value #DEFAULT_PLACEHOLDER_PREFIX}.
	 */
	/** Default placeholder prefix: {@value}. */
	公共静态最终字符串DEFAULT_PLACEHOLDER _PREFIX=“${”；

	/**默认占位符后缀：｛@value｝*/
	公共静态最终字符串DEFAULT_PLACEHOLDER _SUFFIX=“｝”；

	/**默认值分隔符：｛@value｝*/
	公共静态最终字符串DEFAULT_VALUE_SEPARATOR=“：”；


	/**默认值为｛@value#DEFAULT_PLACEHOLDER _PREFIX｝*/
	受保护的字符串占位符前缀=DEFAULT_PLACEHOLDER _PREFIX；

	/**默认为｛@value#DEFAULT_PLACEHOLDER _SUFFIX｝*/
	受保护的字符串占位符后缀=DEFAULT_PLACEHOLDER _SUFFIX；

	/**默认值为｛@value#DEFAULT_value_SEPARATOR｝*/
	@可为空
	受保护的字符串值SEPARATOR=DEFAULT_VALUE_SEPARATOR；

	protected boolean trimValues=false；

	@可为空
	protected字符串nullValue；

	protected boolean ignoreUnsolvablePlaceholders=false；

	@可为空
	private字符串beanName；

	@可为空
	私有BeanFactory BeanFactory；


	/**
	 *设置占位符字符串开头的前缀。
	 *默认值为｛@value#default_PLACEHOLDER _PREFIX｝。
	 */
	public void setPlaceholderPrefix(String placeholderPrefix) {
		this.placeholderPrefix = placeholderPrefix;
	}

	/**
	 * Set the suffix that a placeholder string ends with.
	 * The default is {@value #DEFAULT_PLACEHOLDER_SUFFIX}.
	 */
	/**
	 *设置占位符字符串结尾的后缀。
	 *默认值为｛@value#default_PLACEHOLDER _SUFFIX｝。
	 */
	public void setPlaceholderSuffix(String placeholderSuffix) {
		this.placeholderSuffix = placeholderSuffix;
	}

	/**
	 * Specify the separating character between the placeholder variable
	 * and the associated default value, or {@code null} if no such
	 * special character should be processed as a value separator.
	 * The default is {@value #DEFAULT_VALUE_SEPARATOR}.
	 */
	/**
	 *指定占位符变量之间的分隔符
	 *以及关联的默认值，如果没有，则为｛@code null｝
	 *特殊字符应作为值分隔符处理。
	 *默认值为｛@value#default_value_SEPARATOR｝。
	 */
	public void setValueSeparator(@Nullable String valueSeparator) {
		this.valueSeparator = valueSeparator;
	}

	/**
	 * Specify whether to trim resolved values before applying them,
	 * removing superfluous whitespace from the beginning and end.
	 * <p>Default is {@code false}.
	 * @since 4.3
	 */
	/**
	 *指定是否在应用解析值之前对其进行修剪，
	 *删除开头和结尾多余的空白。
	 *＜p＞默认值为｛@code false｝。
	 *@自4.3
	 */
	public void setTrimValues(boolean trimValues) {
		this.trimValues = trimValues;
	}

	/**
	 * Set a value that should be treated as {@code null} when resolved
	 * as a placeholder value: e.g. "" (empty String) or "null".
	 * <p>Note that this will only apply to full property values,
	 * not to parts of concatenated values.
	 * <p>By default, no such null value is defined. This means that
	 * there is no way to express {@code null} as a property value
	 * unless you explicitly map a corresponding value here.
	 */
	/**
	 *设置一个在解析时应被视为｛@code null｝的值
	 *作为占位符值：例如“”（空字符串）或“null”。
	 *＜p＞注意，这只适用于完整的属性值，
	 *而不是连接值的部分。
	 *＜p＞默认情况下，未定义此类空值。这意味着
	 *无法将｛@code null｝表示为属性值
	 *除非在此显式映射相应的值。
	 */
	public void setNullValue(String nullValue) {
		this.nullValue = nullValue;
	}

	/**
	 * Set whether to ignore unresolvable placeholders.
	 * <p>Default is "false": An exception will be thrown if a placeholder fails
	 * to resolve. Switch this flag to "true" in order to preserve the placeholder
	 * String as-is in such a case, leaving it up to other placeholder configurers
	 * to resolve it.
	 */
	/**
	 *设置是否忽略不可解析的占位符。
	 *＜p＞默认值为“false”：如果占位符失败，将引发异常
	 *解决。将此标志切换为“true”以保留占位符
	 *在这种情况下，字符串保持原样，由其他占位符配置器决定
	 *解决它。
	 */
	public void setIgnoreUnresolvablePlaceholders(boolean ignoreUnresolvablePlaceholders) {
		this.ignoreUnresolvablePlaceholders = ignoreUnresolvablePlaceholders;
	}

	/**
	 * Only necessary to check that we're not parsing our own bean definition,
	 * to avoid failing on unresolvable placeholders in properties file locations.
	 * The latter case can happen with placeholders for system properties in
	 * resource locations.
	 * @see #setLocations
	 * @see org.springframework.core.io.ResourceEditor
	 */
	/**
	 *只需要检查我们没有解析自己的bean定义，
	 *以避免财产文件位置中无法解析的占位符失败。
	 *后一种情况可能发生在中系统财产的占位符
	 *资源位置。
	 *@参见#setLocations
	 *@参见org.springframework.core.io.ResourceEditor
	 */
	@Override
	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}

	/**
	 * Only necessary to check that we're not parsing our own bean definition,
	 * to avoid failing on unresolvable placeholders in properties file locations.
	 * The latter case can happen with placeholders for system properties in
	 * resource locations.
	 * @see #setLocations
	 * @see org.springframework.core.io.ResourceEditor
	 */
	/**
	 *只需要检查我们没有解析自己的bean定义，
	 *以避免财产文件位置中无法解析的占位符失败。
	 *后一种情况可能发生在中系统财产的占位符
	 *资源位置。
	 *@参见#setLocations
	 *@参见org.springframework.core.io.ResourceEditor
	 */
	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}


	protected void doProcessProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
			StringValueResolver valueResolver) {

		BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);

		String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
		for (String curName : beanNames) {
			// Check that we're not parsing our own bean definition,
			// 检查我们没有解析自己的bean定义，
			// to avoid failing on unresolvable placeholders in properties file locations.
			// 以避免财产文件位置中无法解析的占位符失败。
			if (!(curName.equals(this.beanName) && beanFactoryToProcess.equals(this.beanFactory))) {
				BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(curName);
				try {
					visitor.visitBeanDefinition(bd);
				}
				catch (Exception ex) {
					throw new BeanDefinitionStoreException(bd.getResourceDescription(), curName, ex.getMessage(), ex);
				}
			}
		}

		// Resolve placeholders in alias target names and aliases as well.
		// 解析别名目标名称和别名中的占位符。
		beanFactoryToProcess.resolveAliases(valueResolver);

		// Resolve placeholders in embedded values such as annotation attributes.
		// 解析嵌入值（如注释属性）中的占位符。
		beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
	}

}
